<?php
namespace Modules\Common\Services;

use Modules\Common\Models\SysRegionModel;

class SysRegionService {
  private function makeRegionList() {
    $findRegion = SysRegionModel::find();
    $regionList = [];
    foreach($findRegion as $region) {
      $pid = 0;
      if(substr($region -> code, 2) !== '0000') {
        $pid = substr($region -> code, 4) === '00'?
          substr($region -> code, 0, 2) . '0000':
          substr($region -> code, 0, 4) . '00';
      }

      $regionList[$region -> code] = [
        'pid' => $pid,
        'value' => $region -> code,
        'label' => $region -> name
      ];
    }
    return $regionList;
  }

  private function makeTree($mode) {
    $regionList = $this -> makeRegionList();

    $resultRegionList = [];
    foreach($regionList as $region) {
      if($region['pid'] === 0) {
        unset($regionList[$region['value']]['pid']);
        if($mode == 1) {
          $resultRegionList[] = &$regionList[$region['value']];
        } else {
          $resultRegionList[$region['value']] = &$regionList[$region['value']];
        }
        continue;
      }

      if(isset($regionList[$region['pid']])) {
        if($mode == 1) {
          $regionList[$region['pid']]['children'][] = &$regionList[$region['value']];
        } else {
          $regionList[$region['pid']]['children'][$region['value']] = &$regionList[$region['value']];
        }
        unset($regionList[$region['value']]['pid']);
      } else {
        continue;
      }
    }
    return $resultRegionList;
  }

  /**
   * @param mode 模式 (1.自增key,2.指定key为code)
   */
  public function getList($mode) {
    return $this -> makeTree($mode);
  }
}
?>